from django.shortcuts import render
from django.http import HttpResponse
from HelloWorld import models


# Create your views here.
# 业务处理逻辑都在views.py文件里。

# user_list = [
#     {"user":"iack", "pwd":"abc"},
#     {"user":"tom", "pwd":"ABC"}
# ]

def display(request):
    # return HttpResponse("Hello world ! ")
    if request.method == "POST":
        user_id = request.POST.get("user_id", None)
        user_name = request.POST.get("user_name", None)
        password = request.POST.get("password", None)
        # temp = {"user":user_name, "pwd":password}
        # user_list.append(temp)
        # 添加数据到sqlite3数据库
        models.UserInfo.objects.create(user_id=user_id,
                                       user_name=user_name,
                                       password=password)
    # 从数据库读取所有数据
    table_userinfo = models.UserInfo.objects.all()

    return render(request, "display.html", {"data": table_userinfo})


def login(request):
    # return HttpResponse("Hello world ! ")
    if request.method == "POST":
        user_id = request.POST.get("logname", None)
        password = request.POST.get("logpass", None)
        # temp = {"user":user_name, "pwd":password}
        # user_list.append(temp)
        # 添加数据到sqlite3数据库
        models.UserInfo.objects.create(user_id=user_id, password=password)

    # 从数据库读取所有数据
    table_userinfo = models.UserInfo.objects.all()

    return render(request, "login.html", {"data": table_userinfo})


def index(request):  # 定义站点首页视图函数
    return render(request, 'index.html')  # 调用模板返回页面内容


def news_list(request, news_type):  # 定义新闻列表视图
    news_dict = {'economic': '经济', 'sport': '体育'}  # 创建参数字典
    return render(request, 'news_list.html', {'news_type': news_dict[news_type]})  # 整合数据并返回页面内容